<template>
  <base-breadcrumb class="UpdatePartyActivity-container fixed-container" :title="breadcrumbTitle">
    <a-spin :spinning="!!loadingState.isDetail">
      <a-card :bordered="false">
        <title-name title="新闻信息" />
        <custom-form
          ref="ruleForm"
          :is-validate="true"
          :edit-model="''"
          :rules="rules"
          :isEmit="false"
          :form="formInfo"
          :form-list="formItemList"
        >
          <!-- 主图上传 -->
          <template v-slot:fileIds>
            <l-table
              ref="upload"
              :disabled="isDisabled"
              :uploadArrys.sync="formInfo.fileList"
              business-code="NEWS01"
              upload-type="image"
              count="12"
              edit-model="2"
              :show-upload-list="false"
              :is-img-remove="true"
            />
          </template>
          <!-- 选择主图 -->
          <template v-slot:imgList>
            <ImageList
              ref="imgList"
              :disabled="isDisabled || (formInfo.sources && formInfo.sources == 2)"
              :file-list="formInfo.fileList"
              @remove="handleRemove"
            />
          </template>
          <!-- 当是来源是oa平台时，显示文章链接 -->
          <template #content>
            <a :href="formInfo.content" target="_blank" style="margin-top: -3px; display: block">查看内容链接</a>
          </template>
        </custom-form>
      </a-card>
      <a-card :bordered="false">
        <title-name title="其他详细信息" />
        <CustomForm :is-validate="true" :edit-model="''" :form="formInfo" :form-list="otherForm" />
      </a-card>
      <div class="tool-btns tool-btns--fixed page-btn-right-top">
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.DRAFT"
          @click="handleSubmit('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="!isDisabled"
          v-btnPermission="'pa_017_pub_05'"
          class="ml12"
          type="primary"
          :loading="loadingState.SUBMITTED"
          @click="handleSubmit('SUBMITTED')"
        >
          发布
        </a-button>
        <a-button class="ml12" type="default" @click="handleClose"> 关闭 </a-button>
      </div>
    </a-spin>
  </base-breadcrumb>
</template>

<script>
import { addData, updateData, getUnitByOrg, getReleaseDetail } from '@/api/partyMasses/partyManage/newsManage.js'
import { NEWS_TYPE, NEWS_SOURCE } from './model.js'
import Moment from 'moment'
import Vue from 'vue'
import ImageList from './ImageList'
import EditorBar from '@/components/Editor/editor'
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import SelectStaffWithTooltip from '@/components/Select/SelectStaffWithTooltip'

export default {
  name: 'UpdateNewsManage',
  components: {
    ImageList
  },
  data() {
    return {
      sled: void 0,
      loadingState: {
        isDetail: false,
        DRAFT: false,
        SUBMITTED: false
      },
      formInfo: {
        fileList: []
      }
    }
  },
  computed: {
    // // 文件列表
    // uploadArrays() {
    //   return this.pageType === 'add' ? this.formInfo?.fileList : []
    // },
    breadcrumbTitle() {
      const map = {
        add: '新增新闻',
        publish: '新闻发布',
        look: '新闻详情'
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    // 新闻信息表单
    formItemList() {
      return [
        {
          label: '新闻标题',
          keyName: 'title',
          type: 'BaseInput',
          disabled: this.isDisabled || this.formInfo?.sources === '2',
          span: 24,
          rules: [{ required: true, message: '请输入', trigger: 'change' }]
        },
        {
          label: '新闻类型',
          keyName: 'type',
          type: 'a-select',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          data: Object.keys(NEWS_TYPE).map((key) => {
            return {
              label: NEWS_TYPE[key],
              value: key
            }
          }),
          attrs: {
            showSearch: true
          }
        },
        {
          label: '作者',
          keyName: this.formInfo?.sources === '2' ? 'authorName' : 'authors',
          type: this.formInfo?.sources === '2' ? 'BaseInput' : SelectStaffWithTooltip,
          disabled: this.isDisabled || this.formInfo?.sources === '2',
          rules: [{ required: true, message: '请选择作者', trigger: 'change' }],
          attrs: {
            mode: 'multiple',
            labelInValue: true,
            maxTagCount: 3
          }
        },
        {
          label: 'oa平台来源',
          keyName: 'departmentOA',
          span: 16,
          hidden: this.formInfo?.sources !== '2',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '来源单位',
          keyName: 'orgId',
          span: this.formInfo?.sources === '2' ? 8 : 16,
          type: TreeSelectOrganization,
          disabled: this.isDisabled,
          attrs: {
            parentDisabled: true
          },
          rules: [{ required: true, message: '请选择', trigger: 'change' }],
          handleChange: (e) => {
            this.formInfo.orgName = e?.name
          }
        },
        {
          label: '报道内容',
          keyName: 'content',
          type: EditorBar,
          slot: this.formInfo?.sources === '2',
          disabled: this.isDisabled,
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          span: 24,
          attrs: {
            isLimit: true,
            maxLength: 50000,
            businessCode: 'NEWS01',
            useCustomImg: true
          }
        },
        {
          slot: true,
          keyName: 'fileIds',
          label: '主图上传',
          hidden: this.formInfo?.sources === '2',
          span: 24
        },
        {
          slot: true,
          keyName: 'imgList',
          label: '主图选择',
          span: 24
        }
      ]
    },
    // 其他详细信息表单
    otherForm() {
      return [
        {
          label: '创建人',
          keyName: 'createUserName',
          type: 'BaseInput',
          hidden: this.formInfo?.sources === '2',
          disabled: true
        },
        {
          label: '创建时间',
          keyName: 'createTime',
          type: 'BaseInput',
          hidden: this.formInfo?.sources === '2',
          disabled: true
        },
        {
          label: '发布时间',
          keyName: 'releaseTime',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '数据来源',
          keyName: 'sourcesName',
          type: 'BaseInput',
          disabled: true
        },
        {
          label: '创建部门',
          keyName: 'departmentName',
          hidden: this.formInfo?.sources === '2',
          type: 'BaseInput',
          disabled: true,
          span: 16
        }
      ]
    },
    rules() {
      const map = {}
      this.formItemList.map((item) => {
        if (item.rules) {
          map[item.keyName] = item.rules
        }
      })
      return map
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    handleRemove(data) {
      this.$refs.upload.deleteFiles(data)
    },
    async getDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id
        }
        this.loadingState.isDetail = true
        const res = await getReleaseDetail(params)
        this.formInfo = {
          ...this.formInfo,
          ...res.data,
          authors: res.data.author?.split(',').map((i, idex) => {
            return {
              key: i,
              label: res.data.authorName?.split('，')?.[idex]
            }
          }),
          fileList: res.data?.list || [],
          sourcesName: NEWS_SOURCE[res.data?.sources]
        }
      } catch (e) {
        console.error(e)
      }
      this.loadingState.isDetail = false
    },
    filterSource(val) {
      return NEWS_SOURCE[val] || ''
    },
    async getUnitByOrgReq() {
      try {
        const userInfo = Vue.getAcloudProvider().getUserInfo()
        const res = await getUnitByOrg({
          orgId: userInfo?.currentPost?.deptId
        })
        this.formInfo = {
          ...this.formInfo,
          departmentName: res?.data?.message || '',
          departmentId: userInfo?.currentPost?.deptId
        }
      } catch (e) {
        console.error(e)
      }
    },
    /**
     * 页面初始化
     */
    initPage() {
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      const curDate = Moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      this.formInfo = {
        ...this.formInfo,
        createUserName: userInfo.name,
        createTime: curDate,
        sourcesName: this.filterSource('1')
      }
      if (this.pageType === 'add') {
        this.getUnitByOrgReq()
      } else {
        this.getDetailReq()
      }
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'DRAFT': 保存草稿  'SUBMITTED'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'SUBMITTED') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      const imgList = this.$refs.imgList
      const mainId = imgList.getValue()
      // if (actionName === 'SUBMITTED' && this.formInfo.sources !== '2') {
      //   if (!mainId || !this.formInfo.fileList.length) {
      //     this.$message.warning('请上传并选择主图')
      //     return
      //   }
      // }
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const params = {
          ...this.formInfo,
          author: this.formInfo.authors?.map((i) => i.key)?.join(),
          authorName: this.formInfo.authors?.map((i) => i.label)?.join('，'),
          // parentId:actionName === 'DRAFT' && this.$route.query.releaseStatus == 1 ? this.formInfo.id : void 0, // 已发布新闻保存草稿需要加上父级标识
          releaseStatus: actionName === 'SUBMITTED' || this.$route.query.releaseStatus == 1 ? 1 : 0, // 发布状态 0:未发布;1:已发布
          topStatus: this.formInfo.topStatus || 0, // 置顶状态 0:未置顶;1:已置顶
          list: this.formInfo.fileList?.map((item) => {
            const { fileId, fileName, commonId } = item
            return {
              fileId,
              fileName,
              commonId,
              main: item.commonId === mainId
            }
          })
        }
        // 若是保存草稿操作，则根据发布状态设置草稿状态为：1、已发布的草稿；2、未发布的草稿
        if (actionName === 'DRAFT' && this.$route.query.releaseStatus == 1) {
          params.draftStatus = 1
        }
        delete params.sourcesName
        delete params.authors
        const fn = this.pageType === 'add' ? addData : updateData
        await fn(params)
        this.$message.success(actionName === 'DRAFT' ? '保存成功' : '发布成功')
        this.handleClose()
      } catch (e) {
        console.error(e)
      }
      this.loadingState[actionName] = false
    },
    handleClose() {
      this.$close()
    }
  }
}
</script>

<style>
</style>
